﻿using System;
using System.ComponentModel;
using DevExpress.ExpressApp.Model;
using DevExpress.ExpressApp.Win.Templates.ActionContainers;
using DevExpress.XtraBars;
using DevExpress.ExpressApp;
using Hdt.TransOcean.Dal;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Grid;
using System.Windows.Forms;
using System.Data;
using DevExpress.XtraEditors;
using DevExpress.Utils.Menu;
using DevExpress.XtraGrid.Views.Layout.Modes;
using System.Collections.Generic;

namespace Hdt.TransOcean.Presentation
{
    public partial class FormInvoice : DevExpress.ExpressApp.Win.Templates.XtraFormTemplateBase, ISupportClassicToRibbonTransform
    {
        private EOperation _operation;
        private EInvoiceType _invoiceType;
        private Common comm = new Common();
        private string invCode = "";
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            CheckTransformToRibbon();
        }
        protected override IModelFormState GetFormStateNode()
        {
            if (View != null)
            {
                return TemplatesHelper.GetFormStateNode(View.Id);
            }
            else
            {
                return base.GetFormStateNode();
            }
        }
        public override void SetSettings(IModelTemplate modelTemplate)
        {
            base.SetSettings(modelTemplate);
            formStateModelSynchronizerComponent.Model = GetFormStateNode();
        }
        [Obsolete("Use the DetailViewForm() constructor"), Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
        public FormInvoice(XafApplication application) : this() { }
        public FormInvoice()
        {
            InitializeComponent();
        }

        private int GetRowHandleByColumnValue(IList<Employee> view, string ColumnFieldName, object value)
        {
            int result = GridControl.InvalidRowHandle;
            //for (int i = 0; i < view.RowCount; i++)
            //    if (view.GetDataRow(i)[ColumnFieldName].Equals(value))
            //        return i;
            for (int i = 0; i < view.Count; i++)
            {
                //DataRow dr = view.Rows[i];
                if (view[i].code.ToString() == value.ToString())
                    return i;
            }
            return result;
        }

        public void BindingInvoice(string invoiceCode)
        {
            Dao dao = new Dao();
            Invoice inv = Dao.SelectInvoice(invoiceCode)[0];

            txtInvoiceDate.Text = inv.invoiced_date.ToString();
            gridLookUpEditSalesman.EditValue = inv.user_code;
            gridLookUpEditBusinessman.EditValue = inv.saleman;
            gridLookUpEditCustomer.EditValue = inv.customer_code;
            txtCustomerAddress.Text = inv.customer_address;
            txtCustomerName.Text = inv.customer_name;
            txtCustomerPhone.Text = inv.customer_phone;
            if (inv.sale_invoice !="")
                gridLookUpEditSaleInvoice.EditValue = inv.sale_invoice;

            rdoType.EditValue = inv.item_type;
            rdoType.SelectedIndex = inv.item_type - 1;

            txtPaidTotalAmount.Text = inv.paid_amount.ToString();
            //Detail
            IList<InvoiceDetail> invDetail = Dao.SelectInvoiceDetail(invoiceCode);
            gridControlInvoiceDetail.DataSource = invDetail;
        }

        public FormInvoice(EOperation operation,string code=null)
        {
            InitializeComponent();
            this._operation = operation;
            Dao dao = new Dao();
            Presentation.DisplayButtonByOperation(hdtManageControl1, operation);
            if (operation == EOperation.Edit)
            {
                txtCode.Enabled = false;
                if (!String.IsNullOrEmpty(code))
                {
                   // BindingInvoice(code);
                    txtCode.Text = code;
                    invCode = code;
                    gridViewInvoiceDetail.OptionsBehavior.AllowAddRows=DevExpress.Utils.DefaultBoolean.False;
                }
            }
        }

   

        private void LoadCustomer()
        {
            Dao dao = new Dao();
            gridLookUpEditCustomer.Properties.DataSource = Dao.SelectCustomer();
            gridLookUpEditCustomer.Properties.DisplayMember = "name";
            gridLookUpEditCustomer.Properties.ValueMember = "code";
        }
        private void LoadSalesMan()
        {
            Dao dao = new Dao();
            gridLookUpEditSalesman.Properties.DataSource = Dao.SelectEmployee(3);
            gridLookUpEditSalesman.Properties.DisplayMember = "name";
            gridLookUpEditSalesman.Properties.ValueMember = "code";
        }
        private void LoadBusinessMan()
        {
            Dao dao = new Dao();
            gridLookUpEditBusinessman.Properties.DataSource = Dao.SelectEmployee(1);//dao.GetListData("Employee"); //dao.SelectEmployee(); ;
            gridLookUpEditBusinessman.Properties.ValueMember = "code";
            gridLookUpEditBusinessman.Properties.DisplayMember = "name";
        }
        private void LoadAirLines()
        {
            Dao dao = new Dao();
            gridLookUpEditAirline.DataSource = Dao.SelectAirline();
            gridLookUpEditAirline.DisplayMember = "name";
            gridLookUpEditAirline.ValueMember = "code";
        }
        private void LoadJournal()
        {
            Dao dao = new Dao();
            gridLookupEditJourney.DataSource = Dao.SelectJourney();
            gridLookupEditJourney.DisplayMember = "name";
            gridLookupEditJourney.ValueMember = "code";
        }

        private void CreateGrid()
        {
            DataTable tb = new DataTable();
            tb.Columns.Add("invoice_code");
            tb.Columns.Add("item_code");
            tb.Columns.Add("item_name");
            tb.Columns.Add("journey_code");
            tb.Columns.Add("airline_code");
            tb.Columns.Add("ticket_code");
            tb.Columns.Add("quantity");
            tb.Columns.Add("amount");
            tb.Columns.Add("commission");
            tb.Columns.Add("sale_price");
            tb.Columns.Add("status_quantity");
            tb.Columns.Add("status_amount");
            tb.Columns.Add("service_fee");
            tb.Columns.Add("airline_service_fee");

            tb.Columns.Add("total_amount");
            tb.Columns.Add("airline_commission");

            tb.Columns.Add("passenger_name");
            tb.Columns.Add("passenger_phone");
            tb.Columns.Add("passenger_email");
            tb.Columns.Add("passenger_id_card");

            tb.Columns.Add("depart_date");
            tb.Columns.Add("return_date");

            tb.Columns.Add("currency_code");
            tb.Columns.Add("rate");
            tb.Columns.Add("status");
            tb.Columns.Add("status_invoice");
            tb.Columns.Add("description");
            tb.Columns.Add("rank");

            gridControlInvoiceDetail.DataSource = tb;
        }
        private void CreateGridCustomer()
        {
            gridColumnCustomerCode.FieldName = "code";
            gridColumnCustomerName.FieldName = "name";
            gridColumnCustomerAddress.FieldName = "address";
            gridColumnCustomerPhone.FieldName = "telephone";
            gridColumnCustomerMobile.FieldName = "mobile";
            gridColumnCustomerEmail.FieldName = "email";
            gridColumnCustomerFax.FieldName = "fax";
            gridColumnCustomerDescription.FieldName = "description";
        }
        private void CreateGridSalesMan()
        {
            GridColumn colEmpCodeSM = gridLookUpEditSalesman.Properties.View.Columns.AddField("code");
            colEmpCodeSM.VisibleIndex = 0;
            colEmpCodeSM.Width = 75;
            colEmpCodeSM.Caption = "Mã nhân viên";
            GridColumn colEmpNameSM = gridLookUpEditSalesman.Properties.View.Columns.AddField("name");
            colEmpNameSM.VisibleIndex = 1;
            colEmpNameSM.Width = 150;
            colEmpNameSM.Caption = "Tên nhân viên";
            GridColumn colEmpPhoneSM = gridLookUpEditSalesman.Properties.View.Columns.AddField("phone");
            colEmpPhoneSM.VisibleIndex = 2;
            colEmpPhoneSM.Width = 75;
            colEmpPhoneSM.Caption = "Số điện thoại";
        }
        private void CreateGridBusinessMan()
        {
            GridColumn colEmpCode = gridLookUpEditBusinessman.Properties.View.Columns.AddField("code");
            colEmpCode.VisibleIndex = 0;
            colEmpCode.Width = 75;
            colEmpCode.Caption = "Mã nhân viên";
            GridColumn colEmpName = gridLookUpEditBusinessman.Properties.View.Columns.AddField("name");
            colEmpName.VisibleIndex = 1;
            colEmpName.Width = 150;
            colEmpName.Caption = "Tên nhân viên";
            GridColumn colEmpPhone = gridLookUpEditBusinessman.Properties.View.Columns.AddField("phone");
            colEmpPhone.VisibleIndex = 2;
            colEmpPhone.Width = 75;
            colEmpPhone.Caption = "Số điện thoại";
        }
        private void CreateGridAirlines()
        {
            GridColumn colCode = gridLookUpEditAirline.View.Columns.AddField("code");
            colCode.VisibleIndex = 0;
            colCode.Width = 75;
            colCode.Caption = "Mã";
            GridColumn colName = gridLookUpEditAirline.View.Columns.AddField("name");
            colName.VisibleIndex = 1;
            colName.Width = 100;
            colName.Caption = "Tên";
            GridColumn colDesc = gridLookUpEditAirline.View.Columns.AddField("description");
            colDesc.VisibleIndex = 2;
            colDesc.Width = 120;
            colDesc.Caption = "Diễn giải";
        }
        private void CreateGriJournal()
        {
            GridColumn col1 = gridLookupEditJourney.View.Columns.AddField("code");
            col1.VisibleIndex = 0;
            col1.Width = 75;
            col1.Caption = "Mã";
            GridColumn col2 = gridLookupEditJourney.View.Columns.AddField("name");
            col2.VisibleIndex = 1;
            col2.Width = 100;
            col2.Caption = "Tên";
            GridColumn col3 = gridLookupEditJourney.View.Columns.AddField("description");
            col3.VisibleIndex = 2;
            col3.Width = 120;
            col3.Caption = "Diễn giải";
        }
        
        private void FormSaleInvoice_Load(object sender, EventArgs e)
        {
            // Customer
            LoadCustomer();
            CreateGridCustomer();
            
            // Sales man
            LoadSalesMan();
            CreateGridSalesMan();

            // Business man
            LoadBusinessMan();
            CreateGridBusinessMan();

            // Journal
            LoadJournal();
            CreateGriJournal();

            //Airlines
            LoadAirLines();
            CreateGridAirlines();

            if (this._operation == EOperation.New)
                txtCode.Text = Dao.GetAutoCode("Invoice");//txtCode.Text = this.Tag + Common.Right("00000" + (int.Parse(Dao.GetCodeCurrent(this.Name, this.Tag.ToString())) + 1).ToString(), lengthCode);
               
            // Set Currency
            repositoryItemComboBoxCurrency.Items.AddRange(new string [] {"VND", "USD"});
            txtInvoiceDate.EditValue = DateTime.Now;
            CreateGrid();
            if(this._operation==EOperation.Edit)
                BindingInvoice(invCode);
        }

        //public void BindSaleInvoiceDetailGrid(GridControl grid, string invoiceCode)
        //{
        //    Dao dao = new Dao();
        //    BindingSource bsDataSource = new BindingSource();

        //    var airlines = dao.SelectSaleInvoiceDetail(invoiceCode);
        //    bsDataSource.DataSource = airlines;
        //    grid.DataSource = bsDataSource;

        //    gridColumnJourneyCode.FieldName = "code";
        //    gridColumnItemName.FieldName = "name";
        //    gridColumnAirline.FieldName = "airline";
        //    gridColumnQuantity.FieldName = "quantity";
        //    gridColumnSalePrice.FieldName = "sale_price";
        //    gridColumnCommission.FieldName = "commission";
        //    gridColumnAmount.FieldName = "amount";
        //}

        private void hdtManageControl1_HdtNewButtonClick()
        {
            txtInvoiceDate.Text = DateTime.Now.ToString();
        }

        private void hdtManageControl1_HdtSaveButtonClick()
        {
            if (ValidateData() == 1)
            {
                return;
            }
            string message = "Lưu thành công!";
            Dao dao = new Dao();
            Invoice invoice = new Invoice();
            InvoiceDetail[] invoiceDetails = null;
            int j = 0;
            Decimal amount = 0;
            Decimal totalAmount = 0;
            Decimal airCommission = 0;
            Decimal commission = 0;

            //kiem tra trung hoa don
            string hdNew = txtCode.Text;
            int flagError = Dao.CheckExistsInvoiceCode(txtCode.Text);
            if (flagError == 1 && this._operation==EOperation.New)
            {
                hdNew =  Dao.GetAutoCode("Invoice");//this.Tag + Common.Right("00000" + (int.Parse(Common.Right(dao.GetMaxCode(this.HtmlText, this.Tag.ToString()), lengthCode)) + 1).ToString(), lengthCode);
                if (MessageBox.Show(this, "Mã hóa đơn " + txtCode.Text + " đã tồn tại, bạn có muốn đổi qua mã khác " + hdNew, "thông báo", MessageBoxButtons.YesNo) == DialogResult.No)
                {
                    hdNew = txtCode.Text;
                }
            }
            // Add information to Invoice Deatail
            invoiceDetails = new InvoiceDetail[gridViewInvoiceDetail.RowCount];
            for (int i = 0; i < gridViewInvoiceDetail.RowCount; i++)
            {
                if (this._operation == EOperation.Edit)
                {
                    InvoiceDetail d =(InvoiceDetail) gridControlInvoiceDetail.Views[0].GetRow(i);
                    if (d != null)
                    {
                        InvoiceDetail item = new InvoiceDetail();
                        item.item_code = d.journey_code;
                        item.item_name = d.journey_code;
                        item.journey_code = d.journey_code;
                        item.invoice_code = hdNew; //txtCode.Text;
                        item.airline_code = d.airline_code;
                        item.ticket_code = d.ticket_code;
                        item.sale_price = d.sale_price;
                        item.quantity =d.quantity;
                        item.commission = d.commission;
                        item.amount = d.amount;

                        item.status_quantity = d.status_quantity;
                        item.status_amount =d.status_quantity;
                        item.service_fee = d.service_fee;
                        item.total_amount = d.total_amount;
                        item.airline_commission = d.airline_commission;
                        item.passenger_name = d.passenger_name;
                        item.passenger_phone = d.passenger_phone;
                        item.passenger_email = d.passenger_email;
                        item.passenger_id_card = d.passenger_id_card;
                        item.depart_date = d.depart_date;
                        item.return_date =d.return_date;
                        item.currency_code = d.currency_code;
                        item.rate = d.rate;
                        item.status = dInvoiceType.Sales;
                        item.status_invoice = d.status_invoice;
                        item.description = d.description;
                        item.rank = d.rank;
                        item.order_num = d.order_num;

                        amount += item.amount * item.rate;  // VND
                        airCommission += item.airline_commission * item.rate; // VND
                        commission += item.commission * item.rate; // VND
                        if (Presentation.ValidInvoiceDetail(item))
                        {
                            invoiceDetails[j++] = item;
                        }
                    }

                }
                else
                {
                    DataRow row = gridViewInvoiceDetail.GetDataRow(i);
                    if (row != null)
                    {
                        InvoiceDetail item = new InvoiceDetail();
                        item.item_code = row["journey_code"].ToString();
                        item.item_name = row["journey_code"].ToString();
                        item.journey_code = row["journey_code"].ToString();
                        item.invoice_code = hdNew; //txtCode.Text;
                        item.airline_code = row["airline_code"].ToString();
                        item.ticket_code = row["ticket_code"].ToString();
                        item.sale_price = Decimal.Parse(Common.IIF(row["sale_price"].ToString() == "", 0, row["sale_price"]).ToString());
                        item.quantity = Int16.Parse(Common.IIF(row["quantity"].ToString() == "", 0, row["quantity"]).ToString());
                        item.commission = Decimal.Parse(Common.IIF(row["commission"].ToString() == "", 0, row["commission"]).ToString());
                        item.amount = Decimal.Parse(Common.IIF(row["amount"].ToString() == "", 0, row["amount"]).ToString());

                        item.status_quantity = Int16.Parse(Common.IIF(row["status_quantity"].ToString() == "", 0, row["status_quantity"]).ToString());
                        item.status_amount = Decimal.Parse(Common.IIF(row["status_amount"].ToString() == "", 0, row["status_amount"]).ToString());
                        item.service_fee = Decimal.Parse(Common.IIF(row["service_fee"].ToString() == "", 0, row["service_fee"]).ToString());
                        item.total_amount = Decimal.Parse(Common.IIF(row["total_amount"].ToString() == "", 0, row["total_amount"]).ToString());
                        item.airline_commission = Decimal.Parse(Common.IIF(row["airline_commission"].ToString() == "", 0, row["airline_commission"]).ToString());
                        item.passenger_name = row["passenger_name"].ToString();
                        item.passenger_phone = row["passenger_phone"].ToString();
                        item.passenger_email = row["passenger_email"].ToString();
                        item.passenger_id_card = row["passenger_id_card"].ToString();
                        item.depart_date = DateTime.Parse(row["depart_date"].ToString());
                        item.return_date = DateTime.Parse(row["return_date"].ToString());
                        item.currency_code = row["currency_code"].ToString();
                        item.rate = Decimal.Parse(Common.IIF(row["rate"].ToString() == "", 0, row["rate"]).ToString());
                        item.status = dInvoiceType.Sales;
                        item.status_invoice = row["status_invoice"].ToString();
                        item.description = row["description"].ToString();
                        item.rank = row["rank"].ToString();
                        item.order_num = i;

                        amount += item.amount * item.rate;  // VND
                        airCommission += item.airline_commission * item.rate; // VND
                        commission += item.commission * item.rate; // VND
                        if (Presentation.ValidInvoiceDetail(item))
                        {
                            invoiceDetails[j++] = item;
                        }
                    }
                }
                
            }// for (int i = 0; i < gridViewInvoiceDetail.RowCount; i++)

            // Add information to Invoice
            invoice.code = hdNew;
            invoice.invoiced_date = txtInvoiceDate.DateTime;
            invoice.updated_date = DateTime.Now;
            invoice.created_date = DateTime.Now;

            string customerCode = "";
            string businessManCode = "";
            string salesManCode = "";
            if (this._operation == EOperation.Edit)
            {
                businessManCode = gridLookUpEditBusinessman.EditValue.ToString() ?? string.Empty;
                customerCode = gridLookUpEditCustomer.EditValue.ToString() ?? string.Empty;
                salesManCode = gridLookUpEditSalesman.EditValue.ToString() ?? string.Empty;
            }
            else
            {
                int rowHandle = gridLookUpEditCustomer.Properties.View.LocateByValue(0, gridLookUpEditCustomer.Properties.View.Columns[gridLookUpEditCustomer.Properties.ValueMember], gridLookUpEditCustomer.EditValue);
                customerCode = gridLookUpEditCustomer.Properties.View.GetRowCellDisplayText(rowHandle, "code");

                rowHandle = gridLookUpEditBusinessman.Properties.View.LocateByValue(0, gridLookUpEditBusinessman.Properties.View.Columns[gridLookUpEditBusinessman.Properties.ValueMember], gridLookUpEditBusinessman.EditValue);
                businessManCode = gridLookUpEditBusinessman.Properties.View.GetRowCellDisplayText(rowHandle, "code");

                rowHandle = gridLookUpEditSalesman.Properties.View.LocateByValue(0, gridLookUpEditSalesman.Properties.View.Columns[gridLookUpEditSalesman.Properties.ValueMember], gridLookUpEditSalesman.EditValue);
                salesManCode = gridLookUpEditSalesman.Properties.View.GetRowCellDisplayText(rowHandle, "code");
            }
            
            totalAmount = decimal.Parse(Common.IIF(txtTotalAmount.Text == "", 0, txtTotalAmount.Text).ToString());
            invoice.customer_code = customerCode;
            invoice.customer_name = txtCustomerName.Text;
            invoice.customer_address = txtCustomerAddress.Text;
            invoice.customer_phone = txtCustomerPhone.Text;
            invoice.user_code = salesManCode;
            invoice.saleman = businessManCode;
            invoice.item_type =int.Parse(rdoType.Properties.Items[rdoType.SelectedIndex].Value.ToString());
            invoice.description = txtDescription.Text;
            invoice.amount = amount;
            invoice.airline_commission = airCommission;
            invoice.commission = commission;
            invoice.total_amount = totalAmount;
            invoice.status = 1;
            invoice.invoice_type = dInvoiceType.Sales;
            invoice.extended_debt_day_num = 0;
            invoice.sale_invoice = "";
            invoice.paid_amount = decimal.Parse(Common.IIF(txtPaidTotalAmount.Text == "", 0, txtPaidTotalAmount.Text).ToString());
            invoice.payment_method = 0;
            try
            {
                if (Presentation.ValidInvoice(invoice) == true)
                {
                    if (this._operation == EOperation.Edit)
                    {
                        Dao.UpdateInvoice(invoice, invoiceDetails);
                    }
                    else if (this._operation == EOperation.New)
                    {
                        int isSuccess = dao.InsertInvoice(invoice, invoiceDetails);
                        if (isSuccess == 1) // Insert Success
                        {
                            //string newCode = "";
                            ////newCode = //Common.Right("00000" + (int.Parse(Common.Right(invoice.code, lengthCode))).ToString(), lengthCode);
                            //dao.SetCodeCurrent("Invoice", Dao.GetAutoCodePrefix("Invoice"), newCode);

                            AutoCode ac = new AutoCode();
                            ac.current_value = txtCode.Text.ToString().Substring(2, txtCode.Text.ToString().Length - 2);
                            Dao.UpdateAutoCodeByTable(ac, "Invoice");
                        }
                    }
                }

            }
            catch (Exception e)
            {
                if (e != null)
                {
                    //flag = false;
                    message = e.ToString();
                }
            }
            finally
            {
                Common c = new Common();
                c.SetValueToTableUpdateString(EObject.SaleInvoice.ToString());

                MessageBox.Show(message, "Hóa đơn bán - Lưu");
                gridControlInvoiceDetail.DataSource = null;
                gridLookUpEditCustomer.SelectedText = null;
                gridLookUpEditBusinessman.SelectedText = null;
                gridLookUpEditBusinessman.Focus();
                txtCustomerAddress.Text = "";
                txtCustomerName.Text = "";
                txtCustomerPhone.Text = "";
                txtCode.Text = Dao.GetAutoCode("Invoice");//this.Tag + Common.Right("00000" + (int.Parse(Dao.GetCodeCurrent(this.Name, this.Tag.ToString())) + 1).ToString(), lengthCode);
                txtTotalAmount.Text = "0";
                txtTotalAmountUSD.Text = "0";
                txtPaidTotalAmount.Text = "0";
                txtPaidTotalAmountUSD.Text = "0";
                txtOutstandingAmount.Text = "0";
                txtOutstandingAmountUSD.Text = "0";
                CreateGrid();
            }
        }

        private void hdtManageControl1_HdtEditButtonClick()
        {

        }

        private void hdtManageControl1_HdtDeleteButtonClick()
        {

        }

        private void hdtManageControl1_HdtCloseButtonClick()
        {

        }

        private void hdtManageControl1_HdtExportButtonClick()
        {

        }

        private void hdtManageControl1_HdtImportButtonClick()
        {

        }

        private void gridLookUpEditCustomer_EditValueChanging(object sender, DevExpress.XtraEditors.Controls.ChangingEventArgs e)
        {
            DevExpress.XtraEditors.GridLookUpEdit edit = sender as DevExpress.XtraEditors.GridLookUpEdit;
            Customer customer = edit.Properties.View.GetRow(edit.Properties.View.FocusedRowHandle) as Customer;

            if (customer != null)
            {
                txtCustomerAddress.Text = customer.address.ToString();
                txtCustomerPhone.Text = customer.telephone.ToString();
                txtCustomerName.Text = customer.name.ToString();
            }            
        }

        void GetItemPrice(string journeyCode, string airlineCode)
        {
            //Dao dao = new Dao();
            //Item item = dao.SelectItemByJourneyAndAirline(journeyCode,airlineCode);
            //if (item == null)
            //{
            //    MessageBox.Show("Chọn lại hành trình và hãng hàng không");
            //    return;
            //}
            //gridViewInvoiceDetail.SetRowCellValue(gridViewInvoiceDetail.FocusedRowHandle,"sale_price", item.sale_price);

        }

        public int ValidateData()
        {
            int flagError = 0;
            if (txtCode.Text == "")
            {
                MessageBox.Show("Chưa có mã hóa đơn");
                flagError = 1;
                return flagError;
            }
            ////check Invoice Code
            //Dao dao = new Dao();
            //flagError = dao.CheckInvoiceCode(txtCode.Text);
            //if (flagError == 1)
            //{
            //    MessageBox.Show("Mã hóa đơn "+txtCode.Text+" đã tồn tại, vui lòng chọn mã khác");
            //    return flagError; 
            //}

            int rowHandle;
            string customerCode;
            string businessManCode;
            string salesMan;
            if (this._operation != EOperation.Edit)
            {
                if (gridLookUpEditCustomer.Properties.View.RowCount <= 0)//&& this._operation != EOperation.Edit) || (gridLookUpEditCustomer.Text == "" && this._operation == EOperation.Edit))
                {
                    customerCode = "";
                }
                else
                {
                    rowHandle = gridLookUpEditCustomer.Properties.View.LocateByValue(0, gridLookUpEditCustomer.Properties.View.Columns[gridLookUpEditCustomer.Properties.ValueMember], gridLookUpEditCustomer.EditValue);
                    customerCode = gridLookUpEditCustomer.Properties.View.GetRowCellDisplayText(rowHandle, "code");
                }
                if (gridLookUpEditBusinessman.Properties.View.RowCount <= 0)//&& this._operation != EOperation.Edit) || (gridLookUpEditBusinessman.Text == "" && this._operation == EOperation.Edit))
                {
                    businessManCode = "";
                }
                else
                {
                    rowHandle = gridLookUpEditBusinessman.Properties.View.LocateByValue(0, gridLookUpEditBusinessman.Properties.View.Columns[gridLookUpEditBusinessman.Properties.ValueMember], gridLookUpEditBusinessman.EditValue);
                    businessManCode = gridLookUpEditBusinessman.Properties.View.GetRowCellDisplayText(rowHandle, "code");
                }

                if (gridLookUpEditSalesman.Properties.View.RowCount <= 0)// && this._operation != EOperation.Edit) || (gridLookUpEditSalesman.Text == "" && this._operation == EOperation.Edit))
                {
                    salesMan = "";
                }
                else
                {
                    rowHandle = gridLookUpEditSalesman.Properties.View.LocateByValue(0, gridLookUpEditSalesman.Properties.View.Columns[gridLookUpEditSalesman.Properties.ValueMember], gridLookUpEditSalesman.EditValue);
                    salesMan = gridLookUpEditSalesman.Properties.View.GetRowCellDisplayText(rowHandle, "code");
                }

                if (customerCode == "")
                {
                    MessageBox.Show("Chưa chọn khách hàng");
                    flagError = 1;
                    return flagError;
                }
                if (businessManCode == "")
                {
                    DialogResult digResult =MessageBox.Show("Chưa chọn nhân viên kinh doanh, bạn có muốn tiếp tục", "Thông báo",MessageBoxButtons.OKCancel);
                    if (digResult != DialogResult.OK)
                    {
                        flagError = 1;
                        return flagError;
                    }
                    else
                        flagError = 0;

                    //return flagError;
                }
                //if (salesMan == "")
                //{
                //    MessageBox.Show("Chưa chọn nhân viên bán hàng");
                //    flagError = 1;
                //    return flagError;
                //}
            }

            int dataRowCount = gridViewInvoiceDetail.RowCount;
            for (int i = 0; i < dataRowCount; i++)
            {
                DataRow row = gridViewInvoiceDetail.GetDataRow(i);
                if (row != null)
                {
                    if (row["ticket_code"].ToString() == "")
                    {
                        MessageBox.Show("Chưa nhập mã vé");
                        flagError = 1;
                        return flagError;
                    }
                    if (row["airline_code"].ToString() == "")
                    {
                        MessageBox.Show("Chưa chọn Hãng hàng không");
                        flagError = 1;
                        return flagError;
                    }
                    if (row["journey_code"].ToString() == "")
                    {
                        MessageBox.Show("Chưa chọn hành trình");
                        flagError = 1;
                        return flagError;
                    }
                }
            }

            return flagError;

        }

        public void SetTotalAmount()
        {
            decimal totalAmount = 0;
            decimal totalAmountUSD = 0;
            int dataRowCount = gridViewInvoiceDetail.RowCount;
            for (int i = 0; i < dataRowCount; i++)
            {
                if (this._operation!=EOperation.Edit)
                {
                    DataRow row = gridViewInvoiceDetail.GetDataRow(i);
                    if (row != null)
                    {
                        if (row["currency_code"].ToString() == "VND")
                        {
                            totalAmount += decimal.Parse(row["total_amount"].ToString());
                        }
                        else
                        {
                            totalAmountUSD += decimal.Parse(row["total_amount"].ToString());
                            totalAmount += decimal.Parse(row["total_amount"].ToString()) * decimal.Parse(row["rate"].ToString());
                        }
                    }
                }

                if (this._operation == EOperation.Edit)
                {
                    InvoiceDetail d =(InvoiceDetail) gridControlInvoiceDetail.Views[0].GetRow(i);
                    if (d != null)
                    {
                        if (d.currency_code == "VND")
                        {
                            totalAmount += d.total_amount;
                        }
                        else
                        {
                            totalAmountUSD += d.total_amount;
                            totalAmount += d.total_amount*d.rate;
                        }
                    }
                }
              
            }
            //txtTotalAmount.Properties.FormatEditValue =respo
            txtTotalAmount.Text  = totalAmount.ToString();
            txtTotalAmountUSD.Text = totalAmountUSD.ToString();
            txtOutstandingAmount.Text = (decimal.Parse(Common.IIF(txtTotalAmount.Text == "", 0, txtTotalAmount.Text).ToString()) - decimal.Parse(Common.IIF(txtPaidTotalAmount.Text == "", 0, txtPaidTotalAmount.Text).ToString())).ToString();
        }

        private void gridViewInvoiceDetail_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            int quantity = 0;
            decimal unitPrice = 0;
            decimal lineCommission = 0;
            decimal lineAmount = 0;
            decimal lineTotalAmount = 0;
            decimal lineServiceAmount = 0;
            switch(e.Column.FieldName.ToString())
            {
                case "depart_date":
                    break;

                case "return_date":
                    DateTime dReturnDate = DateTime.Parse( gridViewInvoiceDetail.GetRowCellValue(e.RowHandle, "return_date").ToString());
                    DateTime dDepartDate = DateTime.Parse(gridViewInvoiceDetail.GetRowCellValue(e.RowHandle, "depart_date").ToString());
                    if (dReturnDate < dDepartDate)
                    {
                        XtraMessageBox.Show("[Ngày đến] Invalid Value");
                        gridViewInvoiceDetail.SetRowCellValue(e.RowHandle, "return_date", dDepartDate);
                    }
                    break;

                case "invoice_code":
                    break;
                case "item_code":
                    break;
                case "item_name":
                    break;
                case "journey_code":
                    break;

                case "airline_code":
                    string journeyCode = gridViewInvoiceDetail.GetRowCellValue(e.RowHandle, "journey_code").ToString();
                    string airlineCode = gridViewInvoiceDetail.GetRowCellValue(e.RowHandle, "airline_code").ToString();

                    if (journeyCode != null && airlineCode != null && journeyCode != string.Empty && airlineCode != string.Empty)
                    {
                        GetItemPrice(journeyCode, airlineCode); // lay don gia
                    }

                    goto case "currency_code";
                    //break;

                case "ticket_code":
                    break;

                case "currency_code":
                    decimal rate = 1;
                    Dao dao = new Dao();
                    DateTime invoiceDate = DateTime.Parse (txtInvoiceDate.EditValue.ToString());
                    string airline = gridViewInvoiceDetail.GetRowCellValue(e.RowHandle, "airline_code").ToString();
                    string currency = gridViewInvoiceDetail.GetRowCellValue(e.RowHandle, "currency_code").ToString();
                    rate = dao.SelectRateWithCurrencyCode(airline, currency, invoiceDate.Date );
                    if (currency == "VND")
                        rate = 1;
                    
                    gridViewInvoiceDetail.SetRowCellValue(e.RowHandle, "rate", rate);
                    goto case "sale_price";
                    //break;

                case "quantity":
                case"commission"://giam gia cho khach hang
                case"sale_price":
                    quantity =int.Parse(Common.IIF(gridViewInvoiceDetail.GetRowCellValue(e.RowHandle, "quantity").ToString() == "", 0, gridViewInvoiceDetail.GetRowCellValue(e.RowHandle, "quantity")).ToString())  ;
                    unitPrice=decimal.Parse(Common.IIF(gridViewInvoiceDetail.GetRowCellValue(e.RowHandle, "sale_price").ToString() == "", 0, gridViewInvoiceDetail.GetRowCellValue(e.RowHandle, "sale_price")).ToString());
                    lineCommission = decimal.Parse(Common.IIF(gridViewInvoiceDetail.GetRowCellValue(e.RowHandle, "commission").ToString() == "", 0, gridViewInvoiceDetail.GetRowCellValue(e.RowHandle, "commission")).ToString()); 

                    lineAmount =  unitPrice - lineCommission;// amount = sales_price - comission
                    gridViewInvoiceDetail.SetRowCellValue(gridViewInvoiceDetail.FocusedRowHandle, "amount", lineAmount);

                    lineServiceAmount = decimal.Parse(Common.IIF(gridViewInvoiceDetail.GetRowCellValue(e.RowHandle, "status_amount").ToString() == "", 0, gridViewInvoiceDetail.GetRowCellValue(e.RowHandle, "status_amount")).ToString());
                    lineTotalAmount = lineAmount*quantity ; //+ lineServiceAmount;
                    gridViewInvoiceDetail.SetRowCellValue(e.RowHandle, "total_amount", lineTotalAmount);
                    break;

                case "amount": // amount =  Sale_price - commission
                    quantity = int.Parse(Common.IIF(gridViewInvoiceDetail.GetRowCellValue(e.RowHandle, "quantity").ToString() == "", 0, gridViewInvoiceDetail.GetRowCellValue(e.RowHandle, "quantity")).ToString());
                    lineServiceAmount = decimal.Parse(Common.IIF(gridViewInvoiceDetail.GetRowCellValue(e.RowHandle, "status_amount").ToString() == "", 0, gridViewInvoiceDetail.GetRowCellValue(e.RowHandle, "status_amount")).ToString());
                    lineAmount = decimal.Parse(Common.IIF(gridViewInvoiceDetail.GetRowCellValue(e.RowHandle, "amount").ToString() == "", 0, gridViewInvoiceDetail.GetRowCellValue(e.RowHandle, "amount")).ToString());
                    lineTotalAmount = lineAmount * quantity;//lineAmount + lineServiceAmount;
                    gridViewInvoiceDetail.SetRowCellValue(e.RowHandle, "total_amount", lineTotalAmount);
                    break;

                case "service_fee": 
                case "status_quantity":
                    int status_quantity = int.Parse(Common.IIF(gridViewInvoiceDetail.GetRowCellValue(e.RowHandle, "status_quantity").ToString() == "", 0, gridViewInvoiceDetail.GetRowCellValue(e.RowHandle, "status_quantity")).ToString());
                    decimal service_fee = decimal.Parse(Common.IIF(gridViewInvoiceDetail.GetRowCellValue(e.RowHandle, "service_fee").ToString() == "", 0, gridViewInvoiceDetail.GetRowCellValue(e.RowHandle, "service_fee")).ToString());
                    lineServiceAmount = status_quantity * service_fee;
                    gridViewInvoiceDetail.SetRowCellValue(e.RowHandle, "status_amount", lineServiceAmount);
                   
                    //lineAmount = decimal.Parse(Common.IIF(gridViewInvoiceDetail.GetRowCellValue(e.RowHandle, "amount").ToString() == "", 0, gridViewInvoiceDetail.GetRowCellValue(e.RowHandle, "amount")).ToString());
                    //lineTotalAmount = lineAmount + lineServiceAmount;
                    //gridViewInvoiceDetail.SetRowCellValue(e.RowHandle, "total_amount", lineTotalAmount);
                    break;

                case "status_amount": // service_fee*status_quantity
                    //lineServiceAmount = decimal.Parse(Common.IIF(gridViewInvoiceDetail.GetRowCellValue(e.RowHandle, "status_amount").ToString() == "", 0, gridViewInvoiceDetail.GetRowCellValue(e.RowHandle, "status_amount")).ToString());
                    //lineAmount = decimal.Parse(Common.IIF(gridViewInvoiceDetail.GetRowCellValue(e.RowHandle, "amount").ToString() == "", 0, gridViewInvoiceDetail.GetRowCellValue(e.RowHandle, "amount")).ToString());
                    //lineTotalAmount = lineAmount + lineServiceAmount;
                    //gridViewInvoiceDetail.SetRowCellValue(e.RowHandle, "total_amount", lineTotalAmount);
                    break;

                case "total_amount": // Total_amount = amount + status_amount
                    break;

                case "airline_service_fee":
                    break;

                case "airline_commission":
                    break;

                case "customer":
                    break;

                case "customer_phone":
                    break;

                case "customer_email":
                    break;

                case "customer_id_card":
                    break;
            }
        }

        private void gridViewInvoiceDetail_RowCountChanged(object sender, EventArgs e)
        {
            SetTotalAmount();
        }

        private void gridViewInvoiceDetail_RowUpdated(object sender, DevExpress.XtraGrid.Views.Base.RowObjectEventArgs e)
        {
            SetTotalAmount();
        }

        private void gridViewInvoiceDetail_InitNewRow(object sender, InitNewRowEventArgs e)
        {
            //e.RowHandle 
            gridViewInvoiceDetail.SetRowCellValue(gridViewInvoiceDetail.FocusedRowHandle, "depart_date", DateTime.Now );
            gridViewInvoiceDetail.SetRowCellValue(e.RowHandle, "return_date", DateTime.Now);
            gridViewInvoiceDetail.SetRowCellValue(e.RowHandle, "currency_code", "VND");
            gridViewInvoiceDetail.SetRowCellValue(e.RowHandle, "rate", 1);
            gridViewInvoiceDetail.SetRowCellValue(e.RowHandle, "quantity", 1);
        }

        private void txtPaidTotalAmount_EditValueChanged(object sender, EventArgs e)
        {
            txtOutstandingAmount.Text = (decimal.Parse(Common.IIF(txtTotalAmount.Text == "", 0, txtTotalAmount.Text).ToString()) - decimal.Parse(Common.IIF(txtPaidTotalAmount.Text == "", 0, txtPaidTotalAmount.Text).ToString())).ToString();
        }

        private void txtPaidTotalAmountUSD_EditValueChanged(object sender, EventArgs e)
        {
            txtOutstandingAmountUSD.Text = (decimal.Parse(Common.IIF(txtTotalAmountUSD.Text == "", 0, txtTotalAmountUSD.Text).ToString()) - decimal.Parse(Common.IIF(txtPaidTotalAmountUSD.Text == "", 0, txtPaidTotalAmountUSD.Text).ToString())).ToString();
        }
        
        #region sub Menu
        class RowInfo
        {
            public RowInfo(GridView view, int rowHandle)
            {
                this.RowHandle = rowHandle;
                this.View = view;
            }
            public GridView View;
            public int RowHandle;
        }

        void OnAddRowClick(object sender, EventArgs e)
        {
            DXMenuItem item = sender as DXMenuItem;
            RowInfo info = item.Tag as RowInfo;
            info.View.AddNewRow();
        }
        DXMenuItem CreateRowMenuAddRow(GridView view, int rowHandle)
        {
            DXMenuItem itemMenu = new DXMenuItem("&Thêm dòng", new EventHandler(OnAddRowClick));
            itemMenu.Tag = new RowInfo(view, rowHandle);
            return itemMenu;
        }

        DXMenuCheckItem CreateMergingEnabledMenuItem(GridView view, int rowHandle)
        {
            DXMenuCheckItem checkItem = new DXMenuCheckItem("&Merging Enabled",
            view.OptionsView.AllowCellMerge, null, new EventHandler(OnMergingEnabledClick));
            checkItem.Tag = new RowInfo(view, rowHandle);
            return checkItem;
        }

        //The handler for the MergingEnabled menu item
        void OnMergingEnabledClick(object sender, EventArgs e)
        {
            DXMenuCheckItem item = sender as DXMenuCheckItem;
            RowInfo info = item.Tag as RowInfo;
            info.View.OptionsView.AllowCellMerge = item.Checked;
        }

        // Create a submenu with a single DeleteRow item.
        DXMenuItem CreateRowMenuDeleteRow(GridView view, int rowHandle)
        {
            DXMenuItem itemMenu = new DXMenuItem("&Xoá dòng", new EventHandler(OnDeleteRowClick));
            itemMenu.Tag = new RowInfo(view, rowHandle);//"adadad";       
            return itemMenu;
        }

        ////The handler for the DeleteRow menu item
        void OnDeleteRowClick(object sender, EventArgs e)
        {
            DXMenuItem item = sender as DXMenuItem;
            RowInfo info = item.Tag as RowInfo;
            info.View.DeleteRow(info.RowHandle);
        }
        #endregion

        private void gridViewInvoiceDetail_PopupMenuShowing(object sender, PopupMenuShowingEventArgs e)
        {
            GridView view = sender as GridView;
            // Check whether a row is right-clicked.
            if (e.MenuType == DevExpress.XtraGrid.Views.Grid.GridMenuType.Row)
            {
                int rowHandle = e.HitInfo.RowHandle;
                // Delete existing menu items, if any.
                e.Menu.Items.Clear();
                // Add a submenu with a single menu item.
                e.Menu.Items.Add(CreateRowMenuAddRow(view, rowHandle));
                e.Menu.Items.Add(CreateRowMenuDeleteRow(view, rowHandle));
                // Add a check menu item.
                //DXMenuItem item = CreateMergingEnabledMenuItem(view, rowHandle);
                //item.BeginGroup = true;
                //e.Menu.Items.Add(item);
            }
        }
        private void FormInvoice_Activated(object sender, EventArgs e)
        {
            if (comm.CheckValueInTableUpdateString(this.Name, EObject.Customer.ToString()) == true)//GlobalVariable.strTableUpdate.ToString().Contains(this.Name + "." + EObject.Customer.ToString()) == true)
            {
                LoadCustomer();
                comm.RemoveValueInTableUpdateString(this.Name, EObject.Customer.ToString());
            }

            if (comm.CheckValueInTableUpdateString(this.Name, EObject.Journey.ToString()) == true)//if (GlobalVariable.strTableUpdate.ToString().Contains(this.Name + "." + EObject.Journey.ToString()) == true)
            {
                LoadJournal();
                comm.RemoveValueInTableUpdateString(this.Name, EObject.Journey.ToString());
            }

            if (comm.CheckValueInTableUpdateString(this.Name, EObject.Airline.ToString()) == true) //if (GlobalVariable.strTableUpdate.ToString().Contains(this.Name + "." + EObject.Airline.ToString()) == true)
            {
                LoadAirLines();
                comm.RemoveValueInTableUpdateString(this.Name, EObject.Airline.ToString());
            }
            if (comm.CheckValueInTableUpdateString(this.Name, EObject.Employee.ToString()) == true) //if (GlobalVariable.strTableUpdate.ToString().Contains(this.Name + "." + EObject.Employee.ToString()) == true)
            {
                LoadBusinessMan();
                LoadSalesMan();
                comm.RemoveValueInTableUpdateString(this.Name, EObject.Employee.ToString());
            }
        }
        private void FormInvoice_Deactivate(object sender, EventArgs e)
        {
            comm.RemoveValueInTableUpdateString(this.Name, EObject.Customer.ToString());
            comm.RemoveValueInTableUpdateString(this.Name, EObject.Journey.ToString());
            comm.RemoveValueInTableUpdateString(this.Name, EObject.Item.ToString());
            comm.RemoveValueInTableUpdateString(this.Name, EObject.Employee.ToString());
            comm.RemoveValueInTableUpdateString(this.Name, EObject.SaleInvoice.ToString());
            comm.RemoveValueInTableUpdateString(this.Name, EObject.ReturnInvoice.ToString());
            comm.RemoveValueInTableUpdateString(this.Name, EObject.Airline.ToString());
            comm.RemoveValueInTableUpdateString(this.Name, EObject.User.ToString());
        }        

    }
}
